package com.mxbbx.wdn.dao;

import java.sql.ResultSet;
import java.sql.PreparedStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.mxbbx.wdn.database.DBUtil;
import com.mxbbx.wdn.domain.menu.Menu;
import com.mxbbx.wdn.domain.vo.Page;

/**
 * 菜单管理Dao类
 * 
 * @author 
 * 
 */
public class MenuDao extends BaseDao {
	@Override
	protected Menu handle(ResultSet rs) throws SQLException {
		try {
			Menu menu = new Menu();
			menu.setMenuId(rs.getString("menuId"));
			menu.setMenuPid(rs.getString("menuPid"));
			menu.setMenuName(rs.getString("menuName"));
			menu.setUrl(rs.getString("url"));
			menu.setLevel(rs.getInt("level"));
			return menu;
		} catch (SQLException e) {
			throw new SQLException("结果集转换为对象失败:", e);

		}
	}

	/**
	 * 分页
	 * 
	 * @param sql
	 *            -濡�select * from user where userId=?
	 * @param params
	 * @param page
	 * @param size
	 * @return
	 * @throws SQLException
	 */
	public Page queryOjectsByPage(String sql, Object[] params, int pageNo,
			int size) throws SQLException {
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		Page page = null;
		List<Menu> datas = new ArrayList<Menu>();
		try {
			int start = (pageNo - 1) * size;
			conn = DBUtil.getConn();
			pstmt = conn.prepareStatement(sql + " limit " + start + "," + size);
			int index = 1;
			if (params != null) {
				for (Object param : params) {
					if (param instanceof String) {
						pstmt.setString(index++, (String) param);
					}
					if (param instanceof Integer) {
						pstmt.setInt(index++, (Integer) param);
					}
					if (param instanceof Float) {
						pstmt.setFloat(index++, (Float) param);
					}
				}
			}
			rs = pstmt.executeQuery();
			while (rs.next()) {
				Menu menu = handle(rs);
				datas.add(menu);
			}
			// 统计SQL对应的记录数
			int total = count(sql, params);
			page = new Page(total, pageNo, size, datas);
			return page;
		} catch (SQLException e) {
			throw new SQLException("执行SQL[" + sql + "]失败", e);
		}finally {
			DBUtil.close(rs, pstmt, conn);
		}

	}

}
